<script lang="ts" setup>
  import { ElMessageBox, ElMessage, FormInstance, FormRules } from 'element-plus'
  import { onMounted, reactive, ref, watch } from 'vue'
  import { userInfoResult } from '@/types/user'
  import { addUserService, deleteUserService, updateUserInfoService } from '@/api/user'
  const ruleFormRef = ref<FormInstance>()
  const dialogVisible = ref<boolean>(false)
  const deptCascaderRef = ref()
  const emit = defineEmits(['refreshList'])
  onMounted(() => {})
  const departmentRequiredRule = { required: true, message: '部门管理员必须选择所属部门!', trigger: 'change' }
  const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
    employeeNumber: [
      { required: true, message: '请输入工号', trigger: 'blur' },
      { min: 5, max: 15, message: '工号长度在5到15个字符之间', trigger: 'blur' },
      { pattern: /^[a-zA-Z0-9]+$/, message: '工号只能包含字母和数字', trigger: 'blur' },
    ],
    permissionLevel: [{ required: true, message: '请选择用户权限', trigger: 'change' }],
    departmentId: [],
  })

  const ruleForm = ref<userInfoResult>({
    id: null,
    name: '',
    gender: null,
    employeeNumber: '',
    departmentId: null,
    permissionLevel: null,
    roles: [],
    permissions: [],
  })

  //==============================BEGIN 功能函数====================================

  const handleDeptChange = (deptId: string, deptInfo: any) => {
    ruleForm.value.departmentId = deptId
  }
  function close() {
    // 重置表单数据
    ruleFormRef.value.resetFields()
  }

  const show = (item: any = {}) => {
    dialogVisible.value = true
  }
  // 确认按钮
  const handleConfim = async () => {
    await ruleFormRef.value.validate(async (valid) => {
      if (valid) {
        dialogVisible.value = false
        await addUserService(ruleForm.value)
        ElMessage.success('用户添加成功')
        ruleFormRef.value.resetFields()
        emit('refreshList')
      }
    })
  }
  // 动态监听权限等级的变化，添加/移除所属部门的校验规则
  watch(
    () => ruleForm.value.permissionLevel,
    (newVal) => {
      if (newVal === 1) {
        rules.departmentId = [departmentRequiredRule]
      } else {
        delete rules.departmentId
        ruleFormRef.value?.clearValidate?.(['departmentId'])
      }
    },
  )
  //==================================END 功能函数===================================
  defineExpose({
    show,
  })
</script>
<template>
  <el-dialog v-model="dialogVisible" title="新增用户" width="35%" center @close="close">
    <el-form ref="ruleFormRef" :validate-on-rule-change="false" :model="ruleForm" :rules="rules" label-width="100px" status-icon>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="ruleForm.name" clearable placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="工号" prop="employeeNumber">
        <el-input v-model.trim="ruleForm.employeeNumber" clearable placeholder="请输入工号" />
      </el-form-item>
      <el-form-item label="权限等级" prop="permissionLevel">
        <el-radio-group v-model="ruleForm.permissionLevel">
          <el-radio v-permission="['admin222']" :value="0">管理员</el-radio>
          <el-radio :value="1">部门管理员</el-radio>
          <el-radio :value="2">竞赛教师</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="ruleForm.gender">
          <el-radio :value="0">女</el-radio>
          <el-radio :value="1">男</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所属部门" prop="departmentId">
        <Cascader
          ref="deptCascaderRef"
          v-model="ruleForm.departmentId"
          placeholder="可设置用户所属部门"
          :exclude-id="ruleForm.id"
          @select="handleDeptChange"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer dialog-font">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfim">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped></style>
